package com.qingke.product.dao;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.hibernate.query.Query;

import com.qingke.product.pojo.Goods;

public class ProductDao {
	
	private SessionFactory sf=null;
	private Session session=null;
	
	public ProductDao(){}
	
	{
		sf=new Configuration().configure().buildSessionFactory();
		session=sf.openSession();
	}
	
	public <T> void insert(T t){
		Transaction tx=session.beginTransaction();
		try {

			session.save(t);
			tx.commit();
		} catch (HibernateException e) {
			e.printStackTrace();
			tx.rollback();
		}
	}
	
	public Criteria getCriteria(Class<?> classType){
		DetachedCriteria detachedCriteria =DetachedCriteria.forClass(classType);
		Criteria criteria =detachedCriteria.getExecutableCriteria(session);
		return criteria;
	}
	
	public boolean isGoodsNameExists(String name){
		 Criteria criteria=getCriteria(Goods.class);
		 criteria.add(Restrictions.eq("name", name));
		 List<?> list =criteria.list();
		 if(list.size()>0){
			 return true;
		 }
		 return false;
	}
	
	
	public List<Goods> getAllGoods(){
		Query<Goods> query = session.createQuery("from Goods", Goods.class);
		return query.getResultList();

	}
	
	public boolean insert(String name,String description,String imagePath,int price,int count){
		Goods goods =new Goods();
		goods.setName(name);
		goods.setDescription(description);
		goods.setImagePath(imagePath);
		goods.setPrice(price);
		goods.setCount(count);
		Transaction tx=session.beginTransaction();
		try {
			session.save(goods);
			tx.commit();
		} catch (HibernateException e) {
			e.printStackTrace();
			tx.rollback();
			return false;
		}
		return true;	
	}
	public void close(){
		session.close();
	}
	
	public Goods getGoodsById(int id){
		 Criteria criteria=getCriteria(Goods.class);
		 criteria.add(Restrictions.eq("id", id));
		 List<?> list=criteria.list();
		 Goods goods=null;
		 if(list.size()>0){
			 goods=(Goods)list.get(0);
		 }
		 return goods;
	}
	
	public boolean delete(Goods goods){
		Transaction tx=session.beginTransaction();
		try {

			session.delete(goods);
			tx.commit();
		} catch (HibernateException e) {
			e.printStackTrace();
			tx.rollback();
			return false;
		}
		return true;
	}
	
	public boolean update(Goods goods){
		Transaction tx=session.beginTransaction();
		try {

			session.saveOrUpdate(goods);
			tx.commit();
		} catch (HibernateException e) {
			e.printStackTrace();
			tx.rollback();
			return false;
		}
		return true;
	}

}
